package com.example.performance.jmh.demo.jit;

import org.openjdk.jmh.annotations.*;
import org.openjdk.jmh.infra.Blackhole;
import org.openjdk.jmh.runner.Runner;
import org.openjdk.jmh.runner.RunnerException;
import org.openjdk.jmh.runner.options.Options;
import org.openjdk.jmh.runner.options.OptionsBuilder;

import java.util.concurrent.TimeUnit;

/**
 * @author zpMeng
 * @since 9/18/2024
 */
@BenchmarkMode(Mode.AverageTime)
@Warmup(iterations = 3, time = 300, timeUnit = TimeUnit.MICROSECONDS)
@Measurement(iterations = 3, time = 300, timeUnit = TimeUnit.MICROSECONDS)
@Threads(1)
@Fork(1)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@State(Scope.Thread)
public class AvoidJIT {

    @SuppressWarnings("FieldMayBeFinal")
    private double pi = Math.PI;
    private final double finalPi = Math.PI;

    @Benchmark
    public void baseline() {
        // do nothing, this is JMHSample_02_BenchmarkModes baseline
    }

    /**
     * This is wrong: result is not used and the entire computation is optimized away.
     */
    @SuppressWarnings("ResultOfMethodCallIgnored")
    @Benchmark
    public void measureWrong() {
        Math.log(pi);
    }

    /**
     * use Blank-hole to fix wrong measure
     */
    @Benchmark
    public void measureWrongFix(Blackhole bh) {
        bh.consume(Math.log(pi));
    }

    /**
     * This is correct: the result is being used.
     */
    @Benchmark
    public double measureRight() {
        return Math.log(pi);
    }

    /**
     * This is correct: the result is being used.
     */
    @Benchmark
    public double measureRightImprove() {
        return Math.log(finalPi);
    }

    public static void main(String[] args) throws RunnerException {
        Options options = new OptionsBuilder().include(AvoidJIT.class.getSimpleName())
                .build();
        new Runner(options).run();
    }
}